package com.tensquare.base.service;

import com.tensquare.base.dao.LabelDao;
import com.tensquare.base.pojo.Label;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class LabelService {

    @Autowired
    private LabelDao labelDao;

    @Autowired
    private IdWorker idWorker;


    /**
     * 查询全部
     */
    public List<Label> findAll(){
        return labelDao.findAll();
    }

    /**
     * 根据id查询
     */
    public Label findById(String id){
        return labelDao.findById(id).get();
    }

    /**
     * 增加
     */
    public void add(Label label){
        label.setId(idWorker.nextId() + "");
        labelDao.save(label);
    }

    /**
     * 修改
     */
    public void update(Label label){
        labelDao.save(label);
    }

    /**
     * 删除
     */
    public void deleteById(String id){
        labelDao.deleteById(id);
    }


    private Specification<Label> createSpecification(Label label){

      return  new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {

                List<Predicate> list = new ArrayList<>();
                if(label.getLabelname() != null && !label.getLabelname().equals("")){
                    list.add( cb.like(root.get("labelname").as(String.class), "%" + label.getLabelname() +"%"));
                }
                if(label.getState()!=null && !"".equals(label.getState())){
                    list.add(cb.equal(root.get("state").as(String.class), label.getState()));
                }
                return cb.and(list.toArray(new Predicate[list.size()]));
            }
        };
    }

    public List<Label> findSearch(Label label){
        return labelDao.findAll(createSpecification(label));
    }

    public Page<Label> pageQuery(Label label, int page, int size){
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return labelDao.findAll(createSpecification(label), pageRequest);
    }
}
